﻿using System.IO;
using System.Xml.Serialization;
using System.Data;
using System.Text;
using System.Xml;

namespace FreeADO.Common
{
    public class AnalyzeXML
    {
        /// <summary>  
        /// 序列化类实例为XML  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="obj"></param>  
        /// <returns></returns>  
        public static string SerializeXML<T>(T obj)
        {
            if (obj == null)            
                return null;

            using (StringWriter writer = new StringWriter())
            {
                new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
                return writer.ToString().Replace("encoding=\"utf-16\"", "")
                    .Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"","")
                    .Replace(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
                //return writer.ToString();//默认utf-16
            }
        }

        public static string ToXml( DataSet ds)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (TextWriter streamWriter = new StreamWriter(memoryStream))
                {
                    var xmlSerializer = new XmlSerializer(typeof(DataSet));
                    xmlSerializer.Serialize(streamWriter, ds);
                    return Encoding.UTF8.GetString(memoryStream.ToArray());
                }
            }
        }
        #region 注释
        /*
        public static string SerializeXML<T>(T obj)
        {
            if (obj == null)
                return null;

            //XmlSerializer serializer = new XmlSerializer(typeof(T));
            //XmlWriterSettings settings = new XmlWriterSettings();
            //settings.Encoding = new UnicodeEncoding(true, true); // no BOM in a .NET string
            //settings.Indent = false;
            //settings.OmitXmlDeclaration = false;

            using (StringWriter writer = new StringWriter())
            {
                //using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
                //        serializer.Serialize(xmlWriter, obj);                
                //return writer.ToString();

                new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
                return writer.ToString().Replace("encoding=\"utf-16\"", "");
                //return writer.ToString();//默认utf-16
            }
        }*/
        #endregion
    }
}
